module(..., package.seeall)

require "http"
require "nvm"
require "logGenerator"
require "earthquakeWaring"
nvm.init("config.lua", true)
local httpRequestTaskName, sysTime, logMsg, errorMsg = "", "", "", ""
local function cbFnc(result, prompt, head, body)
    log.info("cbFnc start")
    log.info("testHttp.cbFnc result", result)
    log.info("testHttp.cbFnc prompt", prompt)
    local tjsondata, resultBody, errinfo = json.decode(body)
    if result and head then
        for k, v in pairs(head) do
            log.info("httpTask.cbFnc", k .. ": " .. v)
        end
    else
        sysTime = earthquakeWaring.GetSystemTime()
        logMsg = logMsg .. "[" .. sysTime .. "]" .. httpRequestTaskName ..
                     "返回结果:" .. tostring(result) ..
                     "返回结果具体信息:" .. tostring(body) .. "\n"
    end
    if "registerTask" == httpRequestTaskName then
        if result and body then
            log.info("body_test", body)
            log.info("tjsondata_result", resultBody)
            log.info("tjsondata_rrinfo", errinfo)
            local groupId, clientId, uname, pwd =
                tjsondata["Result"]["groupId"], tjsondata["Result"]["clientId"],
                tjsondata["Result"]["uname"], tjsondata["Result"]["pwd"]
            log.info("groupId——MYSF", groupId)
            if groupId ~=nil  then
                nvm.sett("centerConfig", 5, groupId, "SVR")
            end
            if clientId ~=nil  then
                nvm.sett("centerConfig", 6, clientId, "SVR")
            end
            if uname ~=nil  then
                nvm.sett("centerConfig", 7, uname, "SVR")
            end
            if pwd ~=nil  then
                nvm.sett("centerConfig", 8, pwd, "SVR")
            end
            if groupId ~=nil and clientId ~=nil and uname ~=nil and pwd ~=nil then
                sys.restart("注册成功，重启使参数生效")
            end
            log.info("registerTask.cbFnc", "bodyLen=" .. body:len(),
                    "body:" .. tostring(body))

        else
            sysTime = earthquakeWaring.GetSystemTime()
            logMsg = logMsg .. "[" .. sysTime .. "]" .. httpRequestTaskName ..
                         "返回结果:" .. tostring(result) ..
                         "返回结果具体信息:" .. tostring(body) .. "\n"
        end
    elseif "changeRegisterInfo" == httpRequestTaskName then
        if result and body then
            log.info("changeRegisterInfo.cbFnc", "bodyLen=" .. body:len(),
                     "body:" .. tostring(body))
        else
            sysTime = earthquakeWaring.GetSystemTime()
            logMsg = logMsg .. "[" .. sysTime .. "]" .. httpRequestTaskName ..
                         "返回结果:" .. tostring(result) ..
                         "返回结果具体信息:" .. tostring(body) .. "\n"
        end
    elseif "PauseResumeServiceTask" == httpRequestTaskName then
        if result and body then
            log.info("PauseResumeServiceTask.cbFnc", "bodyLen=" .. body:len(),
                     "body:" .. tostring(body))
        else
            sysTime = earthquakeWaring.GetSystemTime()
            logMsg = logMsg .. "[" .. sysTime .. "]" .. httpRequestTaskName ..
                         "返回结果:" .. tostring(result) ..
                         "返回结果具体信息:" .. tostring(body) .. "\n"
        end
    elseif "AuthorizationApplicationUpdateServiceTask" == httpRequestTaskName then
        if result and body then
            log.info("body_test", body)
            log.info("tjsondata_result", resultBody)
            log.info("tjsondata_rrinfo", errinfo)
            local scope, mqtthost, topic, port, Result, scopeLast = "", "", "",
                                                                    "",
                                                                    tjsondata["Result"],
                                                                    ""
            log.info("Result", tostring(Result))
            if Result then
                for i = 1, #Result, 1 do
                    scope = Result[i]["scope"]
                    if "EEW" == scope then
                        mqtthost = "tcp://" .. Result[i]["mqtthost"]
                        port = Result[i]["port"]
                        topic = Result[i]["topic"]
                        if "" == scopeLast then
                            scopeLast = scope
                        else
                            scopeLast = scopeLast .. "," .. scope
                        end
                        nvm.sett("centerConfig", 10, mqtthost, "SVR")
                        nvm.sett("centerConfig", 14, port, "SVR")
                        nvm.sett("centerConfig", 11, topic, "SVR")
                    end
                    if "EQR" == scope then
                        mqtthost = "tcp://" .. Result[i]["mqtthost"]
                        port = Result[i]["port"]
                        topic = Result[i]["topic"]
                        if "" == scopeLast then
                            scopeLast = scope
                        else
                            scopeLast = scopeLast .. "," .. scope
                        end
                        nvm.sett("centerConfig", 12, topic, "SVR")
                    end
                    if "ACK" == scope then
                        mqtthost = "tcp://" .. Result[i]["mqtthost"]
                        port = Result[i]["port"]
                        topic = Result[i]["topic"]
                        if "" == scopeLast then
                            scopeLast = scope
                        else
                            scopeLast = scopeLast .. "," .. scope
                        end
                        nvm.sett("centerConfig", 13, topic, "SVR")
                    end
                    if Result[i]["ftpHost"] then
                        nvm.sett("centerConfig", 16, Result[i]["ftpHost"], "SVR")
                    end
                    if Result[i]["password"] then
                        nvm.sett("centerConfig", 19, Result[i]["password"],
                                 "SVR")
                    end
                    if Result[i]["ftpPort"] then
                        nvm.sett("centerConfig", 17, Result[i]["ftpPort"], "SVR")
                    end
                    if Result[i]["username"] then
                        nvm.sett("centerConfig", 18, Result[i]["username"],
                                 "SVR")
                    end
                end
                sys.restart("授权成功，重启设备使参数生效！")
            else
                sysTime = earthquakeWaring.GetSystemTime()
                logMsg =
                    logMsg .. "[" .. sysTime .. "]" .. httpRequestTaskName ..
                        "返回结果:" .. tostring(result) ..
                        "返回结果具体信息:" .. tostring(body) .. "\n"
            end
            if "" ~= scopeLast then
                nvm.sett("centerConfig", 9, scopeLast, "SVR")
                nvm.sett("centerConfig", 10, mqtthost, "SVR")
                nvm.sett("centerConfig", 14, port, "SVR")
            end
        else
            sysTime = earthquakeWaring.GetSystemTime()
            logMsg = logMsg .. "[" .. sysTime .. "]" .. httpRequestTaskName ..
                         "返回结果:" .. tostring(result) ..
                         "返回结果具体信息:" .. tostring(body) .. "\n"
        end
    elseif "AuthorizationQueryServiceTask" == httpRequestTaskName then
        if result and body then
            sysTime = earthquakeWaring.GetSystemTime()
            logMsg = logMsg .. "[" .. sysTime .. "]" ..
                         "授权查询是否成功:" .. tostring(result) ..
                         "授权查询返回结果:" .. tostring(body) .. "\n"
        end
    elseif "AuthorizationRevocationServiceTask" == httpRequestTaskName then
        sysTime =  earthquakeWaring.GetSystemTime()
        logMsg =
            logMsg .. "[" .. sysTime .. "]" .. "授权撤销是否成功:" ..
                tostring(result) .. "授权撤销返回结果:" ..
                tostring(body) .. "\n"

    elseif "earthquakeWarningReport" == httpRequestTaskName then
        if result and body then
            sysTime = earthquakeWaring.GetSystemTime()
            logMsg = logMsg .. "[" .. sysTime .. "]" .. httpRequestTaskName ..
                         "返回结果:" .. tostring(result) ..
                         "返回结果具体信息:" .. tostring(body) .. "\n"
            log.info("httpTask.cbFnc", "bodyLen=" .. body:len(),
                     "body:" .. tostring(body))
        end
    elseif "registerTaskNewSt" == httpRequestTaskName then
        if result and body then
            log.info("body_test", body)
            log.info("tjsondata_result", resultBody)
            log.info("tjsondata_rrinfo", errinfo)
            local groupId, clientId, uname, deviceSecret =
                tjsondata["Result"]["groupId"], tjsondata["Result"]["clientId"],
                tjsondata["Result"]["uname"],
                tjsondata["Result"]["deviceSecret"]
            log.info("groupId——MYSF", groupId)
            nvm.sett("centerConfig", 5, groupId, "SVR")
            nvm.sett("centerConfig", 6, clientId, "SVR")
            nvm.sett("centerConfig", 7, uname, "SVR")
            nvm.set("deviceSecret", deviceSecret)
            log.info("registerTask.cbFnc", "bodyLen=" .. body:len(),
                     "body:" .. tostring(body))
        else
            sysTime = earthquakeWaring.GetSystemTime()
            logMsg = logMsg .. "[" .. sysTime .. "]" .. httpRequestTaskName ..
                         "返回结果:" .. tostring(result) ..
                         "返回结果具体信息:" .. tostring(body) .. "\n"
        end
    elseif "getToken" == httpRequestTaskName then
        if result and body then
            log.info("body_test", body)
            log.info("tjsondata_result", resultBody)
            log.info("tjsondata_rrinfo", errinfo)
            local token = tjsondata["Result"]["token"]
            nvm.set("token", token)
            log.info("registerTask.cbFnc", "bodyLen=" .. body:len(),
                     "body:" .. tostring(body))
        else
            sysTime = earthquakeWaring.GetSystemTime()
            logMsg = logMsg .. "[" .. sysTime .. "]" .. httpRequestTaskName ..
                         "返回结果:" .. tostring(result) ..
                         "返回结果具体信息:" .. tostring(body) .. "\n"
        end
    elseif "AuthorizationRevocationServiceTaskNewSt" == httpRequestTaskName then
        if result and body then
            log.info("body_test", body)
            log.info("tjsondata_result", resultBody)
            log.info("tjsondata_rrinfo", errinfo)
            local scope, mqtthost, topic, port, Result, scopeLast = "", "", "",
                                                                    "",
                                                                    tjsondata["Result"],
                                                                    ""
            log.info("Result", tostring(Result))
            if Result then
                for i = 1, #Result, 1 do
                    scope = Result[i]["scope"]
                    if "EEW" == scope then
                        mqtthost = "tcp://" .. Result[i]["mqtthost"]
                        port = Result[i]["port"]
                        topic = Result[i]["topic"]
                        if "" == scopeLast then
                            scopeLast = scope
                        else
                            scopeLast = scopeLast .. "," .. scope
                        end
                        nvm.sett("centerConfig", 10, mqtthost, "SVR")
                        nvm.sett("centerConfig", 14, port, "SVR")
                        nvm.sett("centerConfig", 11, topic, "SVR")
                    end
                    if "EQR" == scope then
                        mqtthost = "tcp://" .. Result[i]["mqtthost"]
                        port = Result[i]["port"]
                        topic = Result[i]["topic"]
                        if "" == scopeLast then
                            scopeLast = scope
                        else
                            scopeLast = scopeLast .. "," .. scope
                        end
                        nvm.sett("centerConfig", 12, topic, "SVR")
                    end
                    if "ACK" == scope then
                        mqtthost = "tcp://" .. Result[i]["mqtthost"]
                        port = Result[i]["port"]
                        topic = Result[i]["topic"]
                        if "" == scopeLast then
                            scopeLast = scope
                        else
                            scopeLast = scopeLast .. "," .. scope
                        end
                        nvm.sett("centerConfig", 13, topic, "SVR")
                    end
                    if Result[i]["ftpHost"] then
                        nvm.sett("centerConfig", 16, Result[i]["ftpHost"], "SVR")
                    end
                    if Result[i]["topic"] then
                        nvm.sett("centerConfig", 11, Result[i]["topic"], "SVR")
                    end
                    if Result[i]["ftpPort"] then
                        nvm.sett("centerConfig", 17, Result[i]["ftpPort"], "SVR")
                    end
                end
                sys.restart("授权成功，重启使参数生效")
            else
                sysTime = earthquakeWaring.GetSystemTime()
                logMsg =
                    logMsg .. "[" .. sysTime .. "]" .. httpRequestTaskName ..
                        "返回结果:" .. tostring(result) ..
                        "返回结果具体信息:" .. tostring(body) .. "\n"
            end
            if "" ~= scopeLast then
                nvm.sett("centerConfig", 9, scopeLast, "SVR")
                nvm.sett("centerConfig", 10, mqtthost, "SVR")
                nvm.sett("centerConfig", 14, port, "SVR")
            end
        end
    elseif "verifyTask" == httpRequestTaskName then
        sysTime = earthquakeWaring.GetSystemTime()
        logMsg = logMsg .. "[" .. sysTime .. "]" .. httpRequestTaskName ..
                     "(验签)" .. "返回结果:" .. tostring(result) ..
                     "返回结果具体信息:" .. tostring(body) .. "\n"
        log.info("resultBody", resultBody)
        if result and body then
            log.info("body_test", body)
            log.info("tjsondata_result", resultBody)
            log.info("tjsondata_rrinfo", errinfo)

            log.info("verifyTask.cbFnc", "bodyLen=" .. body:len(),
                     "body:" .. tostring(body))
        end
    end
    logGenerator.generateLogTask(logMsg, "log")
end
-- 数据安全验签功能
function dataSafeVerification(url, rcvTaskName)
    log.info("数据安全验签功能")
    httpRequestTaskName = rcvTaskName
    http.request("GET", url, nil, nil, nil, 30000, cbFnc)
end
-- 如下示例代码是利用multipart/form-data模式，上传2参数和1个照片文件
function postMultipartFormData(url, cert, params, contentType, timeout,
                               rcvFileName)
    local boundary, body, k, v, kk, vv =
        "--------------------------" .. os.time() .. rtos.tick(), {}
    for k, v in pairs(params) do
        if k == "texts" then
            local bodyText = ""
            for kk, vv in pairs(v) do
                bodyText = bodyText .. "--" .. boundary ..
                               "\r\nContent-Disposition: form-data; name=\"" ..
                               kk .. "\"\r\n\r\n" .. vv .. "\r\n"
            end
            body[#body + 1] = bodyText
        elseif k == "files" then
            for kk, vv in pairs(v) do
                print(kk, vv)
                body[#body + 1] = "--" .. boundary ..
                                      "\r\nContent-Disposition: form-data; name=\"" ..
                                      "file" .. "\"; filename=\"" .. kk ..
                                      "\"\r\nContent-Type: " ..
                                      contentType[vv:match("%.(%w+)$")] ..
                                      "\r\n\r\n"
                body[#body + 1] = {file = vv}
                body[#body + 1] = "\r\n"
            end
        end
    end
    body[#body + 1] = "--" .. boundary .. "--\r\n"
    http.request("POST", url, cert, {
        ["Content-Type"] = "multipart/form-data; boundary=" .. boundary,
        ["Connection"] = "keep-alive"
    }, body, timeout, cbFnc, rcvFileName)
end

function urlencodeTab(params)
    local msg = {}
    for k, v in pairs(params) do
        table.insert(msg, string.urlEncode(k) .. '=' .. string.urlEncode(v))
        table.insert(msg, '&')
    end
    table.remove(msg)
    return table.concat(msg)
end

-- 如下示例代码是利用x-www-form-urlencoded模式，上传3个参数
function postApplicationJsonData(url, cert, body, timeout, rcvTaskName)
    log.info("注册任务进入http请求")
    log.info("url", url)
    httpRequestTaskName = rcvTaskName
    http.request("POST", url, cert, {
        ["Authorization"] = "Basic jffdsfdsfdsfdsfjakljfdoiuweonlkdsjdsjapodaskdsf",
        ["Content-Type"] = "application/x-www-form-urlencoded"
    }, urlencodeTab(body), timeout, cbFnc)
end

-- 如下示例代码是利用application/json模式，进行地震预警上报
function earthquakeWarningReport(url, cert, body, timeout, rcvTaskName)
    httpRequestTaskName = rcvTaskName
    http.request("POST", url, cert, {
        ["Authorization"] = "Basic jffdsfdsfdsfdsfjakljfdoiuweonlkdsjdsjapodaskdsf",
        ["Content-Type"] = "application/x-www-form-urlencoded"
    }, urlencodeTab(body), timeout, cbFnc)
end
